# Maintainer: Konstantin Gizdov < arch at kge dot pw >
# Contributor: Frank Siegert < frank.siegert at googlemail dot com >
# Contributor: Scott Lawrence < bytbox at gmail dot com >
# Contributor: Thomas Dziedzic < gostrc at gmail dot com >
# Contributor: Sebastian Voecking < voeck at web dot de >

pkgbase=root
pkgname=('root' 'root-cuda')
pkgver=6.28.08
pkgrel=1
pkgdesc='C++ data analysis framework and interpreter from CERN'
arch=('loong64' 'x86_64')
url='https://root.cern'
license=('LGPL2.1' 'GPL' 'custom:University of California and Stanford University License')
options=(!lto)
makedepends=(
    'ccache'
    'cern-vdt'
    'chromium'
    'cfitsio'
    'cmake'
    'cuda'
    'cudnn'
    'gcc-fortran'
    'gcc12-fortran'
    'git'
    'go'
    'libxml2'
    'libmariadbclient'
    'ocaml'
    'ocaml-ctypes'
    'openmp'
    'openmpi'
    'openssl'
    'openui5'
    'postgresql-libs'
    'pythia8>=8.2.40-1'
    'python-pygments'
    'qt5-webengine'
    'sqlite'
    'unuran'
    'vc'
    'xrootd>5'
    'z3'
)
depends=(
    'blas'
    'desktop-file-utils'
    'fcgi'
    'fftw'
    'ftgl'
    'giflib'
    'gl2ps'
    'glew'
    'graphviz'
    'gsl'
    'hicolor-icon-theme'
    'libafterimage'
    'librsvg'
    'liburing'
    'libxpm'
    'nlohmann-json'
    'pcre'
    'python'
    'python-numpy'
    'tbb'
    'tex-gyre-fonts'
    'unixodbc'
    'xxhash>=0.6.5-1'
    'zstd'
)
optdepends=(
    'cern-vdt: Add a set of fast and vectorisable mathematical functions'
    'chromium: Support for WebGUI'
    'cfitsio: Read images and data from FITS files'
    'libmariadbclient: MySQL support'
    'libxml2: XML parser interface'
    'openmp: Support OpenMP extensions in Minuit2'
    'openmpi: Support OpenMPI extensions in Minuit2'
    'openssl: OpenSSL support'
    'openui5: JSROOT support'
    'postgresql-libs: PostgreSQL support'
    'pythia8>=8.2.40-1: Pythia8 EG support'
    'python-pygments: syntax highlighting in interactive console'
    'qt5-webengine: Support for WebGUI'
    'sqlite: SQLite support'
    'tcsh: Legacy CSH support'
    'unuran: Support non-uniform random numbers'
    'vc: Add types for portable and intuitive SIMD programming'
    'xrootd>5: Support remote file server and client'
    'z3: Suuport the Z3 theorem prover'
)
source=(
    "https://root.cern.ch/download/root_v${pkgver}.source.tar.gz"
    'ROOFIT_LICENSE'
    'root.xml'
    'root.pc.tpl'
    'settings.cmake'
    'settings-cuda.cmake'
    'jupyter_notebook_config.py'
    'nbman-for-arch.patch'
    'thisroot.fail'
)
b2sums=('1fa0ea4d214aa021403f5111df9719aa3b22780420e121a74b740f89d4924d3ff7ae50563d7f08147e57b082885b7bb9707e389324919150382ec6dd2b70cf50'
        '5da6218a171ee0fbd7b03518dde22787bb0e478a18dcf227eea4e65598c0a0bb299747c6503ad3026804e1a4dbcf4d2b674b83e6ed6e482dd3d14ceb4646dee8'
        'b5defce795dbfeee75dab0cc4c20ac84fe55cb11e9acdd5e75831b6db98e6190621867a65427ab44d93b6fe30398db6fd191defb029a6dcd0af087c1e5115451'
        '5e4c589fd9e226fcf7ff9ab880687c10ff0f7b7c03fdf12fc477622d6ec291e2dc62e7f5ce7b68856bccf37b64b2f4331f46788548d39fdca57fd832d1f3b437'
        'ccca1ff2bfa3eacafcd4bee1991bdeffa0d87c7c9745e5e39562c0849e591f214c93add14be411aecde5935da326b56dc13a67defe2679697226a7922ddd9917'
        '51976712d41a2dd641e7ea65d8a49f9105e2f3b6c02c24d132ca2bdad68340a43bb7e511a474519258d2932fb62ff1195794618bb411b478029492e5637f8cb9'
        '47a7b4491f1455ddb02c3793c7fbaf05184dba9a5fc9d7378608727e69c778dd5832c49f11f4d2c8204dcffc86fc4786b5616fb381c4e3e629d78db9c86913c5'
        'ec89007c4441d0010c0bfa90ca81e78ceeeb97bacaae2cc4814bd9a781062add80eaa6e4b8cf59c1a61e89ca8a14f3af6f1163766550f6db4154f671e5176d39'
        '3501c944e8cab13fe9f5c8ab75a7cdb4b59bc5b00df4bf45ad246ab8cd6cb1ebde19369bc688458c97ff5f5acd4e86fc19b4c8f57ab4cb422d0a5eacac081138')

get_pyver () {
    python -c 'import sys; print(str(sys.version_info[0]) + "." + str(sys.version_info[1]))'
}

prepare() {
    local src
    for src in "${source[@]}"; do
        src="${src%%::*}"
        src="${src##*/}"
        [[ $src = *.patch ]] || continue
        echo "  -> Applying patch $src..."
        patch -Np1 -i "../$src" -d "${srcdir}/${pkgbase}-${pkgver}"
    done

    # specify some custom flags
    # needed by vc to link properly
    CUSTOM_CMAKE_FLAGS="-DTARGET_ARCHITECTURE:STRING=generic"
    # make sure it finds python
    CUSTOM_CMAKE_FLAGS+=" -DPYTHON_EXECUTABLE:PATH=/usr/bin/python"
    # need to set install prefix like so
    CUSTOM_CMAKE_FLAGS+=" -DINSTALL_PREFIX=/usr"
    export CUSTOM_CMAKE_FLAGS

    # update system flags
    # don't let ROOT play around with lib paths
    export CPPFLAGS="${CPPFLAGS} -DIS_RPATH_BUILD=1"
    # make sure pthread gets detected
    CUSTOM_COMPILER_FLAGS="${CPPFLAGS} -pthread"
    export CFLAGS="${CFLAGS} ${CUSTOM_COMPILER_FLAGS}"
    export CXXFLAGS="${CXXFLAGS} ${CUSTOM_COMPILER_FLAGS}"
    export LDFLAGS="${LDFLAGS} ${CUSTOM_COMPILER_FLAGS}"

    # go flags for built-in clang
    export CGO_LDFLAGS="${LDFLAGS}"
    export GOFLAGS="-buildmode=pie -trimpath -modcacherw"

    # pass CUDA architectures to nvcc calls
    # Not yet supported in root: TBD
    local _cuda_arches=('52' '53' '60' '61' '62' '70' '72' '75' '80' '86' '87' '89' '90')
    local _cuda_arch_vals=''
    for _cuda_arch in "${_cuda_arches[@]}"; do
        _cuda_arch_vals+="${_cuda_arch}-real;${_cuda_arch}-virtual;"
    done
    _cuda_arch_vals="${_cuda_arch_vals:0:-1}"
    export CUSTOM_CUDA_ARCH='-DCMAKE_CUDA_ARCHITECTURES='"${_cuda_arch_vals}"

    cp -r "${pkgbase}-${pkgver}" "${pkgbase}-${pkgver}-cuda"
}

build() {
    ## ROOT
    mkdir -p "${srcdir}/build"
    cd "${srcdir}/build"

    cmake -C "${srcdir}/settings.cmake" \
        ${CUSTOM_CMAKE_FLAGS} \
        "${srcdir}/${pkgbase}-${pkgver}"
    make

    ## ROOT with CUDA
    mkdir -p "${srcdir}/build-cuda"
    cd "${srcdir}/build-cuda"

    CC=/usr/bin/gcc-12 \
    CXX=/usr/bin/g++-12 \
    FC=/usr/bin/f95-12 \
    cmake -C "${srcdir}/settings-cuda.cmake" \
        ${CUSTOM_CMAKE_FLAGS} \
        ${CUSTOM_CUDA_ARCH} \
        "${srcdir}/${pkgbase}-${pkgver}-cuda"
    make
}

_package() {
    local bld_dir="${srcdir}/${1}"
    cd "${bld_dir}"

    make DESTDIR="${pkgdir}" install

    # fix missing hardlinks for genreflex and rootcint
    cd "${pkgdir}"/usr/bin
    ln -f rootcling rootcint
    ln -f rootcling genreflex
    cd "${bld_dir}" # go back

    # rename the modulemap
    mv "${pkgdir}"/usr/include/module.modulemap "${pkgdir}"/usr/include/root.modulemap

    # fix python env call
    sed -e 's/@python@/python/' -i "${pkgdir}/usr/lib/root/cmdLineUtils.py"

    # try to deal with weird PyROOT, PyMVA and JupyROOT stuff
    rm -rf "${pkgdir}/usr/lib/root/__pycache__"
    local _pyver=$(get_pyver)
    local _pydir="${pkgdir}/usr/lib/python${_pyver}/site-packages"
    install -d "${_pydir}"
    find "${pkgdir}/usr/lib/root" -maxdepth 1 -mindepth 1 \( -iname '*py*' -or -name '*Js*' -or -name 'ROOT' -or -name 'DistRDF' \) \
            ! \( -name '*EGPythia8*' -or -iname '*.rootmap' -or -iname '*.pcm' \) -print0 | while read -rd $'\0' _lib; do
        _base=$(basename "${_lib}")
        ln -sf "/usr/lib/root/${_base}" "${pkgdir}/usr/lib/python${_pyver}/site-packages/${_base}"
    done

    # recompile pycache to strip $pkgdir from embedded paths
    python -m compileall -d "/usr/lib/python${_pyver}" \
        "${pkgdir}/usr/lib/python${_pyver}"
    python -O -m compileall -d "/usr/lib/python${_pyver}" \
        "${pkgdir}/usr/lib/python${_pyver}"

    # icon, shortcut and mime
    install -Dm644 "${srcdir}/${pkgbase}-${pkgver}/icons/Root6Icon.png" \
        "${pkgdir}/usr/share/icons/hicolor/48x48/apps/root.png"
    install -Dm644 "${srcdir}/${pkgbase}-${pkgver}/etc/root.desktop" \
        "${pkgdir}/usr/share/applications/root.desktop"
    echo 'Icon=root.png' >> "${pkgdir}/usr/share/applications/root.desktop"
    install -Dm644 "${srcdir}/root.xml" \
        "${pkgdir}/usr/share/mime/packages/root.xml"

    # use a file that pacman can track instead of adding directly to ld.so.conf
    install -d "${pkgdir}/etc/ld.so.conf.d"
    echo '/usr/lib/root' > "${pkgdir}/etc/ld.so.conf.d/root.conf"

    # create pkg-config file
    local _prefix _exec_prefix _bindir _libdir _incdir _pkg_ver _libs _cflags _requires
    _prefix="$("${pkgdir}"/usr/bin/root-config --prefix)"
    _exec_prefix="$("${pkgdir}"/usr/bin/root-config --exec-prefix)"
    _bindir="$("${pkgdir}"/usr/bin/root-config --bindir)"
    _libdir="$("${pkgdir}"/usr/bin/root-config --libdir)"
    _incdir="$("${pkgdir}"/usr/bin/root-config --incdir)"
    _pkg_ver="$(sed -n 's,.*ROOT_RELEASE *\"\(.*\)\".*,\1,p' < "${pkgdir}"/usr/include/RVersion.h)"
    _libs="$("${pkgdir}"/usr/bin/root-config --libs)"
    _cflags="$("${pkgdir}"/usr/bin/root-config --cflags)"
    printf -v _requires '%s,' "${depends[@]}"
    cp "${srcdir}/root.pc.tpl" "${bld_dir}"/
    sed -e "s@_PREFIX@${_prefix}@" -e "s@_EXECPREFIX@${_exec_prefix}@" \
        -e "s@_LIBDIR@${_libdir}@" -e "s@_INCDIR@${_incdir}@" \
        -e "s@_PKGVERSION@${_pkg_ver}@" -e "s@_LIBRARIES@${_libs}@" \
        -e "s@_CFLAGS@${_cflags}@" -e "s@_UPSTREAM_URL@${url}@" \
        -e "s@_REQUIRES@${_requires}@" \
        -i "${bld_dir}/root.pc.tpl"
    install -Dm644 "${bld_dir}/root.pc.tpl" "${pkgdir}/usr/lib/pkgconfig/root.pc"

    # install all licenses & docs
    install -d "${pkgdir}/usr/share/licenses/roofit"
    install "${srcdir}/ROOFIT_LICENSE" "${pkgdir}/usr/share/licenses/roofit/LICENSE"
    install -d "${pkgdir}/usr/share/licenses/${pkgname}"
    ln -s '/usr/share/doc/root/LICENSE' "${pkgdir}/usr/share/licenses/${pkgname}/LICENSE"
    for _fold in fonts js; do
      install -d "${pkgdir}/usr/share/licenses/${pkgname}/${_fold}"
      ln -s "/usr/share/root/${_fold}/LICENSE" "${pkgdir}/usr/share/licenses/${pkgname}/${_fold}"/
    done
    ln -s '/usr/share/licenses/roofit' "${pkgdir}/usr/share/licenses/${pkgname}/roofit"
    if [ "${pkgname}" != "root" ]; then
        ln -s "/usr/share/licenses/${pkgname}" "${pkgdir}/usr/share/licenses/root"
        ln -s "/usr/share/doc/root" "${pkgdir}/usr/share/doc/${pkgname}"
    fi

    # install jupyter kernels and `root --notebook` config
    install -d "${pkgdir}/usr/share/jupyter/kernels"
    ln -s '/etc/root/notebook/kernels/root' "${pkgdir}/usr/share/jupyter/kernels/root"
    install "${srcdir}/jupyter_notebook_config.py" "${pkgdir}/etc/root/notebook"/

    # drop thisroot.* shell files
    rm -rf "${pkgdir}"/usr/bin/thisroot.*
    install -Dm755 "${srcdir}/thisroot.fail" "${pkgdir}/usr/bin/thisroot.sh"
    for suffix in csh fish; do
        ln -s '/usr/bin/thisroot.sh' "${pkgdir}/usr/bin/thisroot.${suffix}"
    done

    # set correct LD_LIBRARY_PATH at runtime
    sed -i.orig \
        -e "s@#Unix.*.Root.DynamicPath:.*@Unix.*.Root.DynamicPath:    .:${_libdir}:/usr/lib@" \
        "${pkgdir}/etc/root/system.rootrc"
}

package_root() {
    optdepends+=('gcc-fortran: Enable the Fortran components of ROOT')
    _package build
}

package_root-cuda() {
    pkgdesc='C++ data analysis framework and interpreter from CERN with GPU (CUDA) features enabled'
    provides=('root')
    conflicts=('root')
    depends+=('cuda' 'cudnn')
    optdepends+=('gcc12-fortran: Enable the Fortran components of ROOT')
    _package build-cuda
}
